package cn.bestick.thirteenKiller.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5
{
    public static String byteArrayToHex(byte[] byteArray)
    {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        char[] resultCharArray = new char[byteArray.length * 2];

        int index = 0;

        byte[] arrayOfByte = byteArray; int j = byteArray.length; for (int i = 0; i < j; i++) { byte b = arrayOfByte[i];

        resultCharArray[(index++)] = hexDigits[(b >>> 4 & 0xF)];

        resultCharArray[(index++)] = hexDigits[(b & 0xF)];
    }

        return new String(resultCharArray);
    }

    public static String fileMD5(String inputFile)
            throws IOException
    {
        int bufferSize = 262144;

        FileInputStream fileInputStream = null;

        DigestInputStream digestInputStream = null;
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");

            fileInputStream = new FileInputStream(inputFile);

            digestInputStream = new DigestInputStream(fileInputStream, messageDigest);

            byte[] buffer = new byte[bufferSize];

            while (digestInputStream.read(buffer) > 0);
            messageDigest = digestInputStream.getMessageDigest();

            byte[] resultByteArray = messageDigest.digest();

            return byteArrayToHex(resultByteArray);
        }
        catch (NoSuchAlgorithmException e)
        {
            return null;
        }
        finally
        {
            try
            {
                digestInputStream.close();
            }
            catch (Exception localException4)
            {
            }

            try
            {
                fileInputStream.close();
            }
            catch (Exception localException5)
            {
            }
        }
    }
}